package com.gitee.hermer.boot.jee.commons.dict;


import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

import com.gitee.hermer.boot.jee.commons.bean.utils.BeanCopyUtils;
import com.gitee.hermer.boot.jee.commons.dict.domain.DictProperties;
import com.gitee.hermer.boot.jee.commons.exception.ErrorCode;
import com.gitee.hermer.boot.jee.commons.exception.PaiUException;
import com.gitee.hermer.boot.jee.commons.log.Logger;
import com.gitee.hermer.boot.jee.commons.utils.JsonUtils;
import com.gitee.hermer.boot.jee.commons.verify.Assert;

public class BootProperties  implements EnvironmentAware{


	private Logger logger = Logger.getLogger(getClass());

	private Map<String,String> params = new HashMap<String, String>();

	@Autowired
	public BootProperties(DictProperties[] properties){
		if(properties == null)
			return;
		for (DictProperties propertie : properties) {
			try {
				params.putAll(BeanCopyUtils.describeMap(propertie));
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
		}
	}

	

	private void containsKey(String key) throws PaiUException{
		if(!params.containsKey(key) && env.containsProperty(key)){
			params.put(key, env.getProperty(key));
		}
		Assert.isTrueCode(params.containsKey(key), ErrorCode.DATA_ERROR,String.format("数据字典KEY[%s]不存在",key));
	}

	public void print(){
		logger.info(JsonUtils.toJSONString(params));
	}


	public String getDictValueString(String key) throws PaiUException{
		return getDictValue(key, "");
	}
	
	public Integer getDictIntegerValue(String key) throws PaiUException{
		return getDictValue(key, 0);
	}

	public Boolean getDictBooleanValue(String key) throws PaiUException{
		return getDictValue(key, false);
	}

	public Double getDictDoubleValue(String key) throws PaiUException{
		return getDictValue(key,0d);
	}
	
	public <T extends Serializable> T getDictValue(String key,T defaultValue) throws PaiUException{
		containsKey(key);
		if(defaultValue instanceof String)
			return (T)MapUtils.getString(params, key, defaultValue.toString());
		else if(defaultValue instanceof Boolean){
			return (T) MapUtils.getBoolean(params, key, Boolean.valueOf(defaultValue.toString()));
		}else if(defaultValue instanceof Double){
			return (T) MapUtils.getDouble(params, key, Double.valueOf(defaultValue.toString()));
		}else if(defaultValue instanceof Integer){
			return (T) MapUtils.getInteger(params, key, Integer.valueOf(defaultValue.toString()));
		}
		return defaultValue;
	}
	


	private Environment env;

	@Override
	public void setEnvironment(Environment arg0) {
		env = arg0;
	}






}
